package cn.xing.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.xing.async.EventModel;
import cn.xing.async.EventProducer;
import cn.xing.async.EventType;
import cn.xing.model.EntityType;
import cn.xing.model.HostHolder;
import cn.xing.model.News;
import cn.xing.service.LikeService;
import cn.xing.service.NewsService;
import cn.xing.util.NewsUtil;

/**
 * Created by nowcoder on 2016/7/13.
 */
@Controller
public class LikeController {
	@Autowired
	LikeService likeService;

	@Autowired
	HostHolder hostHolder;

	@Autowired
	NewsService newsService;

	@Autowired
	EventProducer eventProducer;

	@RequestMapping(path = { "/like" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String like(@Param("newId") int newsId) {
		long likeCount = likeService.like(hostHolder.getUser().getId(), EntityType.ENTITY_NEWS, newsId);
		// 更新喜欢数
		News news = newsService.getById(newsId);
		newsService.updateLikeCount(newsId, (int) likeCount);
		//异步
		eventProducer.fireEvent(new EventModel(EventType.LIKE).setActorId(hostHolder.getUser().getId())
				.setEntityId(newsId).setEntityType(EntityType.ENTITY_NEWS).setEntityOwnerId(news.getUserId()));

		return NewsUtil.getJSONString(0, String.valueOf(likeCount));
	}

	@RequestMapping(path = { "/dislike" }, method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String dislike(@Param("newId") int newsId) {
		long likeCount = likeService.disLike(hostHolder.getUser().getId(), EntityType.ENTITY_NEWS, newsId);
		// 更新喜欢数
		newsService.updateLikeCount(newsId, (int) likeCount);
		return NewsUtil.getJSONString(0, String.valueOf(likeCount));
	}
}
